package com.qf.controller;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    //覆盖service方法:参数带的HttpServletRequest/HttpServletResponse


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            //获取正在运行的类的字节码文件对象
            Class clazz  = this.getClass() ;
            System.out.println(clazz) ;
            //创建子类实例
            Object obj = clazz.newInstance();
            //约定一种访问数据的格式  :举例:http://localhost:8080/Maven_2302_war/user?methodName=add
            //  http://localhost:8080/Maven_2302_war/模块名称?methodName=子类的方法名
            System.out.println(obj) ;
            //获取参数
            String methodName = request.getParameter("methodName");

            if(methodName==null){
                //http://localhost:8080/Maven_2302_war/index  后面没有携带参数名称
                //说明地址栏上面没有约定这个格式: 访问的前台主页
                methodName = "index" ;
            }
            System.out.println(methodName) ;

            //通过字节码文件对象获取成员方法Method类对象
            Method m = clazz.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //取消Java语言访问检查:针对子类方法默认的/私有的/受保护的
            m.setAccessible(true) ;
            //调用
            m.invoke(obj,request,response) ;
        } catch (Exception e) {
            //e.printStackTrace();
           // System.out.println("BaseServlet的反射出现问题了...");

            //抛出一个运行时期异常
            throw new RuntimeException("exception") ;
        }
    }
    public void index(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //
    }
}
